package com.wanxi.util;

import org.springframework.security.crypto.password.PasswordEncoder;
import sun.misc.BASE64Encoder;

import java.security.MessageDigest;

/**
 * @author Li
 * @Date 2023/5/5 13:39
 */
public class MD5 implements PasswordEncoder {
    public static String encoderByMd5(String str) {
        //确定计算方法
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
            BASE64Encoder base64en = new BASE64Encoder();
            //加密后的字符串
            return base64en.encode(md5.digest(str.getBytes("utf-8")));
        } catch (Exception e) {
            e.printStackTrace();
        }
//        如果try报异常，则默认一个密码：aaaaaa
        return "C056Dl/oStNftflbnO6seQ==";
    }

    @Override
    public String encode(CharSequence rawPassword) {
        return encoderByMd5(rawPassword.toString());
    }

    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        return encoderByMd5(rawPassword.toString()).equals(encodedPassword);
    }
}
